package com.csmarket.csmarketbackend.interceptor;

import com.csmarket.csmarketbackend.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils; // 创建 jwtUtils；
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String upgradeHeader = request.getHeader("Upgrade");
//        if ("websocket".equalsIgnoreCase(upgradeHeader)) {
//            // 对于WebSocket握手请求，让其通过，由WebSocketConfigurator处理认证
//            return true;
//        }
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                String username = jwtUtils.parseToken(token);
                request.setAttribute("username", username);
                return true;
            } catch (Exception e) {
                response.setStatus(401);
                return false;
            }
        }

        response.setStatus(401);
        return false;

    }
}
